/*
  preload.js - 渲染进程预加载脚本（上下文隔离）
  仅暴露受控的 window.electronAPI 接口给页面，避免直接 Node 能力泄漏
*/
const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
  getTabsState: () => ipcRenderer.invoke('tabs:getState'),
  onTabsState: (callback) => {
    const listener = (_event, state) => callback(state);
    ipcRenderer.on('tabs:state', listener);
    return () => ipcRenderer.removeListener('tabs:state', listener);
  },
  createTab: (url) => ipcRenderer.send('tab:create', url),
  switchTab: (tabId) => ipcRenderer.send('tab:switch', tabId),
  closeTab: (tabId) => ipcRenderer.send('tab:close', tabId),
  reload: () => ipcRenderer.send('tab:reload'),
  goBack: () => ipcRenderer.send('tab:goBack'),
  goForward: () => ipcRenderer.send('tab:goForward'),
  navigate: (url) => ipcRenderer.send('tab:navigate', url),
  setTopUiHeight: (height) => ipcRenderer.send('ui:setTopHeight', height),
  getCookies: () => ipcRenderer.invoke('tab:getCookies'),
  getCachedCookies: () => ipcRenderer.invoke('cookies:getCached'),
  setCachedCookies: (cookies) => ipcRenderer.invoke('cookies:setCached', cookies),
  getCachedCookiesFor: (urlOrOrigin) => ipcRenderer.invoke('cookies:getCachedFor', urlOrOrigin),
  setCachedCookiesFor: (urlOrOrigin, cookies) => ipcRenderer.invoke('cookies:setCachedFor', urlOrOrigin, cookies),
  getAllCachedCookies: () => ipcRenderer.invoke('cookies:getAllCached'),
  onCookiesUpdated: (callback) => {
    const listener = (_e, payload) => callback(payload);
    ipcRenderer.on('cookies:updated', listener);
    return () => ipcRenderer.removeListener('cookies:updated', listener);
  },
  hasAuthCookies: async () => {
    const list = await ipcRenderer.invoke('cookies:getCached');
    return Array.isArray(list) && list.length > 0;
  },
  hasAuthCookiesFor: async (urlOrOrigin) => {
    const list = await ipcRenderer.invoke('cookies:getCachedFor', urlOrOrigin);
    return Array.isArray(list) && list.length > 0;
  },
  getAuthCookies: async () => {
    try {
      const cached = await ipcRenderer.invoke('cookies:getCached');
      if (Array.isArray(cached) && cached.length > 0) return cached;
      const live = await ipcRenderer.invoke('tab:getCookies');
      if (Array.isArray(live) && live.length > 0) {
        await ipcRenderer.invoke('cookies:setCached', live);
      }
      return Array.isArray(live) ? live : [];
    } catch (_) {
      return [];
    }
  },
  getAuthCookiesFor: async (urlOrOrigin) => {
    try {
      const cached = await ipcRenderer.invoke('cookies:getCachedFor', urlOrOrigin);
      if (Array.isArray(cached) && cached.length > 0) return cached;
      const state = await ipcRenderer.invoke('tabs:getState');
      const active = Array.isArray(state) ? state.find(t => t.isActive) : null;
      const currentUrl = active && active.url ? String(active.url) : '';
      const toOrigin = (() => { try { return new URL(String(urlOrOrigin)).origin.toLowerCase(); } catch { return String(urlOrOrigin || '').toLowerCase(); } })();
      const currentOrigin = (() => { try { return new URL(currentUrl).origin.toLowerCase(); } catch { return ''; } })();
      if (toOrigin && currentOrigin && toOrigin === currentOrigin) {
        const live = await ipcRenderer.invoke('tab:getCookies');
        if (Array.isArray(live) && live.length > 0) {
          await ipcRenderer.invoke('cookies:setCachedFor', urlOrOrigin, live);
          return live;
        }
      }
      return [];
    } catch (_) {
      return [];
    }
  },

  checkForUpdates: () => ipcRenderer.invoke('app:checkForUpdates'),
  onUpdateAvailable: (callback) => ipcRenderer.on('app:updateAvailable', (_e, data) => callback(data)),
  onUpdateNotAvailable: (callback) => ipcRenderer.on('app:updateNotAvailable', (_e, data) => callback(data)),
  onUpdateError: (callback) => ipcRenderer.on('app:updateError', (_e, err) => callback(err)),

  getAppConfig: () => ipcRenderer.invoke('app:getConfig'),

  // 窗口控制（Windows 无边框）
  minimizeWindow: () => ipcRenderer.send('window:minimize'),
  toggleMaximizeWindow: () => ipcRenderer.send('window:toggleMaximize'),
  closeWindow: () => ipcRenderer.send('window:close'),
  isWindowMaximized: () => ipcRenderer.invoke('window:isMaximized'),
  onWindowState: (callback) => {
    const listener = (_e, state) => callback(state);
    ipcRenderer.on('window:state', listener);
    return () => ipcRenderer.removeListener('window:state', listener);
  },
});